package com.yanqu.road.server.cmd.union.cross.trade;

import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.pb.union.UnionTradeProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.union.cross.CrossUnionTradeModule;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

import java.util.List;

@Cmd(code = Protocol.S_UNION_TRADE_ROUTE_PATRONS_SEDN, desc = "(加入路线)门客派遣")
public class PatronsSendCmd extends AbstractCommand {

    private List<Integer> patronsIdList;

    private int routeId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        UnionTradeProto.PatronsSendReqMsg reqMsg = UnionTradeProto.PatronsSendReqMsg.parseFrom(packet.getBytes());
        patronsIdList = reqMsg.getPatronsIdList();
        routeId = reqMsg.getRouteId();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        String unionUid = player.getUserInfo().getUnionUid();
        if(StringUtils.isNullOrEmpty(unionUid)){
            ret = GameErrorCode.E_UNION_NO_JOIN_UNION;
            return;
        }

        List<Integer> hadSend = player.getModule(CrossUnionTradeModule.class).getSendPatronsIdList();
        for(Integer patronsId : patronsIdList){
            if(hadSend.contains(patronsId)) {
                ret = GameErrorCode.E_UNION_TRADE_PATRONS_BEEN_SEND;        //门客已被派遣过
                return;
            }
        }

        UnionTradeProto.PatronsSendCrossReqMsg.Builder crossReq = UnionTradeProto.PatronsSendCrossReqMsg.newBuilder();
        crossReq.setRouteId(routeId);
        PatronsModule patronsModule = player.getModule(PatronsModule.class);
        for (int patronsId : patronsIdList) {
            UserPatrons userPatrons = patronsModule.getUserPatrons(patronsId);
            if(userPatrons != null){
                UnionTradeProto.RouteJoinPatronsTemp.Builder builder = UnionTradeProto.RouteJoinPatronsTemp.newBuilder();
                builder.setPatronsId(patronsId);
                builder.setAbility(userPatrons.getAbility().toString());
                builder.setSkinId(userPatrons.getSkinId());
                crossReq.addPatrons(builder);
            }
        }
        player.sendPacket(Protocol.C_UNION_TRADE_ROUTE_PATRONS_SEND, crossReq);
    }

    @Override
    public void sendData(GamePlayer player) {
        if(ret != 0){
            UnionTradeProto.PatronsSendRespMsg.Builder respMsg = UnionTradeProto.PatronsSendRespMsg.newBuilder();
            respMsg.setRet(ret);
            player.sendPacket(Protocol.U_UNION_TRADE_ROUTE_PATRONS_SEDN, respMsg);
        }
    }
}
